<script setup lang="ts">
import { deviceVerification } from '@/api/login'
import { getQueryString } from '@/utils/globalUtils'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

// 提交按钮加载状态
const loading = ref(false)

const userCode = ref({
  userCode: getQueryString('user_code'),
})

/**
 * 验证设备码
 */
function submit() {
  if (!userCode.value.userCode) {
    ElMessage({
      message: `请输入用户码`,
      type: 'warning',
    })
    return
  }
  loading.value = true
  const data = {
    user_code: userCode.value.userCode,
  }

  deviceVerification(data)
    .then((result: any) => {
      if (result.success) {
        window.location.href = result.data
      }
      else {
        if (result.code === 401) {
          const currentHref = `${window.origin}${window.location.pathname}?user_code=${userCode.value.userCode}`
          ElMessage({
            message: '登录已失效，跳转至登录...',
            type: 'warning',
          })
          window.location.href = `${
            window.origin
          }/login?target=${encodeURIComponent(currentHref)}`
        }
        else {
          ElMessage({
            message: result.message,
            type: 'warning',
          })
        }
      }
    })
    .catch((e: any) => {
      ElMessage({
        message: `提交设备码失败：${e.message || e.statusText}`,
        type: 'warning',
      })
    })
    .finally(() => (loading.value = false))
}

// 如果地址栏有参数直接提交
if (userCode.value.userCode) {
  submit()
}
</script>

<template>
  <main>
    <!-- 提示卡片 -->
    <el-card class="mb-2">
      输入激活码对设备进行授权。
    </el-card>

    <!-- 输入表单 -->
    <el-card>
      <!-- 输入框 -->
      <el-form :model="userCode" label-width="120px">
        <el-form-item label="Activation Code">
          <el-input
            v-model="userCode.userCode"
            placeholder="User Code，格式：XXXX-XXXX，错误的格式后端会报错"
            maxlength="9"
            clearable
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <!-- 提交按钮 -->
      <el-button
        type="primary"
        :loading="loading"
        class="mt-2"
        block
        @click="submit"
      >
        提交
      </el-button>
    </el-card>
  </main>
</template>

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}

b,
h3,
::v-deep(.n-card-header__main) {
  font-weight: bold !important;
}

.mb-2 {
  margin-bottom: 20px;
}
.mt-2 {
  margin-top: 10px;
}
</style>
